package com.cong.security.service.impl;

import com.cong.security.entity.Account;
import com.cong.security.mapper.AccountMapper;
import com.cong.security.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    @Transactional
    public String smsLogin(String mobile) {
        // 用户已经存在，直接登陆系统即可
        if (accountMapper.exist(mobile) > 0) {
            log.info("用户已经存在");
            return "success";
        } else {
            log.info("新用户登陆、创建默认数据");
            accountMapper.insert(new Account(mobile));
            return "success";
        }
    }

    @Override
    public void password(String password) {
        String pwdString = passwordEncoder.encode(password);
        log.info("用户密码重置接口,[{}]密码加密之后:[{}]", password, pwdString);
    }

    @Override
    @Transactional
    public String testSms(String phone, String code) {
        // 验短信验证码
        if (phone.substring(5).equals(code)) {
            // 查询账号信息
            Account account = accountMapper.loginByPhone(phone);
            if (account == null) {
                // 创建用户加入数据库
                account = new Account(phone);
                accountMapper.insert(account);
            }
            // 返回用户标识,用以和第三方账户绑定
            return account.getId();
        } else {
            log.info("短信验证码不匹配,返回上级");
            return "fail";
        }
    }
}
